import collections
class Solution(object):
    def maxNumEdgesToRemove(self, n, edges):
        d1 = collections.defaultdict(set)
        ans1 = [0] * n
        ans2 = [0] * n
        d2 = collections.defaultdict(set)
        d3 = []
        for t, u, v in edges:
            u -= 1
            v -= 1
            if t == 3:
                d3.append([u, v])
                d1[u].add(v)
                d1[v].add(u)
                d2[u].add(v)
                d2[v].add(u)
            if t == 1:
                d1[u].add(v)
                d1[v].add(u)
            if t == 2:
                d2[u].add(v)
                d2[v].add(u)
        def dfs1(last_node, node):
            ans1[node] = 1
            for v in d1[node]:
                if v != last_node and ans1[v] == 0:
                    dfs1(node, v)
        
        def dfs2(last_node, node):
            ans2[node] = 1
            for v in d2[node]:
                if v != last_node and ans2[v] == 0:
                    dfs2(node, v)   
        
        dfs1(-1, 0)
        dfs2(-1, 0)
        p = [i for i in range(n)]
        def find(x):
            if p[x] == x:
                return p[x]
            else:
                p[x] = find(p[x])
                return p[x]
        self.count = 0
        def union(x, y):
            rx = find(x)
            ry = find(y)
            if rx != ry:
                self.count += 1
                if rx < ry:
                    p[ry] = rx
                else:
                    p[rx] = ry 
                
            
        if sum(ans1) == sum(ans2) == n:
            for u,v in d3:
                union(u, v)
            
            need_edges = 2 * (n - 1) - self.count
            return len(edges) - need_edges
        else:
            return -1




data = Solution()
n = 4
edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
print(data.maxNumEdgesToRemove(n, edges))
